# coding=utf8
"""
工程操作
"""
import requests
from config import BaseConfig
from app.extensions.api import api_v1
from app.modules.common.utils import recursive_json_loads
from app.modules.project.models import ProjectOutBeetle
from app.extensions import log
from collections import OrderedDict

TRUNK_LIST = OrderedDict()


def init_app(app, **kwargs):
    from . import resources
    api_v1.add_namespace(resources.api)
    with app.app_context():
        if BaseConfig.GET_TRUNK_LIST:
            getTrunkList()
        pass


def getTrunkList():
    TRUNK_LIST.clear()
    _url = "%s/project/getTrunkNameList" % BaseConfig.BEETLE_API_URL
    _rtn = recursive_json_loads(requests.post(url = _url).content)
    if _rtn.code != 0:
        _msg = "查询主干工程列表失败. %s" % _rtn.desc
        log.error("============== %s ==============" % _msg)
        return {'success': False, 'msg': _msg}
    for _pr in _rtn.data.list:
        TRUNK_LIST[str(_pr.projectName)] = str(_pr.packageType)
        log.info("============== %s:%s ==============" % (_pr.projectName, _pr.packageType))

    _list = ProjectOutBeetle.query.all()
    for _pro in _list:
        TRUNK_LIST[str(_pro.trunk_name)] = str(_pro.package_type)
        log.info("============== %s:%s ==============" % (_pro.trunk_name, _pro.package_type))

    return {'success': True, 'msg': ''}
